<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Article;
use Storage;

class ArticleController extends Controller
{

    public function index()
    {
        $user = \Auth::user();
        return view('admin/manage_article', compact("user"))->withArticles(Article::orderBy('updated_at', 'desc')->get());
    }

    public function create()
    {
        $user = \Auth::user();
        return view('admin/create_article', compact("user"));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|unique:articles|max:255',
            'body' => 'required',
        ]);

        $article = new Article;
        $article->title = $request->get('title');
        $article->body = $request->get('body');

        if ($request->isMethod('post')) {

            $file = $request->file('attach');

            // 文件是否上传成功
            if ($file->isValid()) {

                // 获取文件相关信息
                $originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension();     // 扩展名
                $realPath = $file->getRealPath();   //临时文件的绝对路径
                $type = $file->getClientMimeType();     // image/jpeg

                // 上传文件
                $filename = substr($originalName, 0, strlen($originalName) - strlen($ext) - 1) . '_' . date('Y-m-d-H-i-s') . '-' . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('attach')->put($filename, file_get_contents($realPath));
                if ($bool) {
                    $article->attach = $filename;
                } 

            }

        }

        if ($article->save()) {
            return redirect('article');
        } else {
            return redirect()->back()->withInput()->withErrors('保存失败！');
        }
    }

    public function destroy($id)
    {
        Article::find($id)->delete();
        return redirect()->back()->withInput()->withErrors('删除成功！');
    }

    public function show($id) {
        $user = \Auth::user();
        $article = Article::find($id);

        $user = \Auth::user();
        if ($user->role == 1) {
            return view('student/show_article', compact("user", "article"));
        } else if ($user->role == 2) {
            return view('supervisor/show_article', compact("user", "article"));
        } else if ($user->role == 3) {
            return view('admin/show_article', compact("user", "article"));
        }
    }

}
